package com.lovely3x.loginandresgiter.login;

import android.os.Bundle;
import android.support.annotation.NonNull;

import com.lovely3x.common.activities.BaseLoginActivity;
import com.lovely3x.common.managements.user.IUser;
import com.lovely3x.common.managements.user.UserLoginStateChangedListener;
import com.lovely3x.common.managements.user.UserManager;
import com.lovely3x.common.requests.BaseCodeTable;
import com.lovely3x.loginandresgiter.R;

/**
 * 登陆界面
 * 你需要扩展该类,在需要登陆的时候调用{@link #login(IUser)} 来进行登陆操作
 * 在稍后你会被回调登陆成功{@link #onLoginSuccessful(IUser)}或失败{@link #onLoginFailure(IUser, int)}
 * Created by lovely3x on 16-4-15.
 */
public abstract class SimpleLoginActivity extends BaseLoginActivity {

    private UserLoginStateChangedListener mUserStateListener;

    @Override
    public void onLoginFailure(@NonNull IUser user, int errorCode) {
        dismissProgressCircle();
        showToast(BaseCodeTable.getInstance().getCodeDescription(errorCode));
    }

    @Override
    public void onLoginSuccessful(@NonNull IUser user) {
        dismissProgressCircle();
        if (isHoldHere()) {
            finish();
        } else {
            launchMainActivity();
        }
    }

    /**
     * 启动主界面
     */
    protected abstract void launchMainActivity();

    @Override
    public void login(@NonNull IUser user) {
        super.login(user);
        showProgressCircle(
                getString(R.string.sign_up),
                getString(R.string.signing_please_wait_amoment));
    }

    @Override
    protected void onViewInitialized() {
        UserManager.getInstance().addUserStateChangedListener(mUserStateListener = new UserLoginStateChangedListener() {
            @Override
            public boolean onUserLoginFailure(IUser IUser, int errorCode) {
                SimpleLoginActivity.this.onLoginFailure(IUser, errorCode);
                return false;
            }

            @Override
            public void onUserLoginSuccessful(IUser IUser) {
                SimpleLoginActivity.this.onLoginSuccessful(IUser);
            }

            @Override
            public void onUserLogoutSuccessful(IUser IUser) {

            }

            @Override
            public void onUserLogoutFailure(IUser IUser, int errorCode) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUserStateListener != null) {
            UserManager.getInstance().removeUserStateChangedListener(mUserStateListener);
            mUserStateListener = null;
        }
    }

    @Override
    public void restoreInstanceOnCreateBefore(@NonNull Bundle savedInstance) {

    }

    @Override
    public void restoreInstanceOnCreateAfter(@NonNull Bundle savedInstance) {

    }
}
